package com.cspg.design.ui.gtasks;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.cspg.design.CSPGApplication;
import com.cspg.design.R;
import com.cspg.design.bean.UserInfo;
import com.cspg.design.bean.deviceBean.HotLineWorkPlanBean;
import com.cspg.design.bean.deviceBean.PointDeviceBean;
import com.cspg.design.bean.deviceBean.PolylineDeviceBean;
import com.cspg.design.bean.projectBean.ProjectBean;
import com.cspg.design.bean.shemeBean.MyHighVoltageSchemeBean;
import com.cspg.design.bean.shemeBean.MyLowVoltageSchemeBean;
import com.cspg.design.dao.gen.DaoSession;
import com.cspg.design.dao.gen.HotLineWorkPlanBeanDao;
import com.cspg.design.dao.gen.MyHighVoltageSchemeBeanDao;
import com.cspg.design.dao.gen.MyLowVoltageSchemeBeanDao;
import com.cspg.design.dao.gen.PointDeviceBeanDao;
import com.cspg.design.dao.gen.PolylineDeviceBeanDao;
import com.cspg.design.dao.gen.ProjectBeanDao;
import com.cspg.design.model.User;
import com.cspg.design.presenter.GTaskPresenter;
import com.cspg.design.presenter.ProjectPresenter;
import com.cspg.design.presenter.SchemePresenter;
import com.cspg.design.request.DeviceLibrary;
import com.cspg.design.ui.map.DesignMapActivity;
import com.cspg.design.ui.project.ProjectHotLineWorkActivity;
import com.cspg.design.ui.project.ProjectInfoActivity;
import com.cspg.design.ui.project.ProjectTotal;
import com.cspg.design.ui.schemeActivity.MyHighVoltageSchemeEditActivity;
import com.cspg.design.ui.schemeActivity.MyLowVoltageSchemeEditActivity;
import com.cspg.design.ui.search.SearchActivity;
import com.cspg.design.utils.ActionBarUtil;
import com.cspg.design.utils.StatusBarUtil;
import com.cspg.design.widget.AlertListDialog;
import com.cspg.design.widget.ToastUtils;

import org.greenrobot.greendao.rx.RxQuery;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class GTasksActivity extends AppCompatActivity {

    private ListView mListViewProject;
    private final List<ProjectBean> projectBeanList = new ArrayList<>();
    private DaoSession daoSession;
    private final ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
    private SimpleAdapter adapter ;
    private GTaskPresenter gTaskPresenter;
    private ProjectPresenter gProjectPresenter;
    private DeviceLibrary deviceLibrary;
    //获取方案哭
    private SchemePresenter schemePresenter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_g_tasks);
        StatusBarUtil.setStatusBarColor(this, R.color.colorPrimary);
        ActionBarUtil.setActionBar(this, R.string.wait_work_title);
        daoSession = ((CSPGApplication) getApplication()).getDaoSession();
        mListViewProject = findViewById(R.id.lv_gtasks_project);
        mListViewProject.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ProjectBean projectBean = projectBeanList.get(position);
                choiceScheme(position,projectBean,false);
            }
        });
        LinearLayout searchLinearLayout = findViewById(R.id.lv_gtasks_search);
        searchLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GTasksActivity.this, SearchActivity.class);
                intent.putExtra("type",1);
                startActivity(intent);
            }
        });
        adapter = new SimpleAdapter(GTasksActivity.this, dataList, R.layout.listview_gtasks_project_item,
                new String[]{"title", "name", "status"},
                new int[]{R.id.item_gtasks_project_title, R.id.item_gtasks_project_name, R.id.item_gtasks_project_status}
        );
        mListViewProject.setAdapter(adapter);
        gTaskPresenter = new GTaskPresenter(this,mListViewProject,projectBeanList,dataList,adapter);
        gProjectPresenter = new ProjectPresenter(this);
        schemePresenter = new SchemePresenter(this,null,null);
        schemePresenter.getHighVoltageScheme();
        schemePresenter.getLowVoltageScheme();
        deviceLibrary = new DeviceLibrary(daoSession);
        deviceLibrary.requestPoleLibrary();
        deviceLibrary.requestTransformerLibrary();
        deviceLibrary.requestWireLibrary();
        initData();
    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return super.onSupportNavigateUp();
    }

    private void initData() {
        RxQuery<ProjectBean> projectBeanRxQuery = daoSession.getProjectBeanDao()
                .queryBuilder()
//                .where(ProjectBeanDao.Properties.UserName.eq(UserInfo.getInstance().userName))
                .orderAsc(ProjectBeanDao.Properties.Id).rx();
        projectBeanRxQuery.list().observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<List<ProjectBean>>() {
            @Override
            public void call(List<ProjectBean> projectBeans) {
                for (int i = 0; i < projectBeans.size(); i++) {
                    if(UserInfo.getInstance().role.contains("设计"))
                    {
                        if (projectBeans.get(i).getProjectStatus().equals("done")) {
                            projectBeanList.add(projectBeans.get(i));
                        }
                    }
                    else
                    {
                        if (projectBeans.get(i).getProjectStatus().equals("doing")) {
                            projectBeanList.add(projectBeans.get(i));
                        }
                    }
                    refreshListView();
                }
            }
        });
    }
    private void refreshListView()
    {

        dataList.clear();
        for (int i = 0; i < projectBeanList.size(); i++) {
            HashMap<String, String> hashMap = new HashMap<String, String>();
            hashMap.put("title", projectBeanList.get(i).getProjectTitle());
            hashMap.put("name", projectBeanList.get(i).getProjectName());
            if (UserInfo.getInstance().role.contains("设计"))
            {
                if (projectBeanList.get(i).getProjectStatus().equals("doing"))
                {
                    hashMap.put("status", "未完成勘查");
                    continue;
                }
                else if (projectBeanList.get(i).getProjectStatus().equals("done"))
                {
                    hashMap.put("status", "待评审");
                }
            }
            else
            {
                if (projectBeanList.get(i).getProjectStatus().equals("doing"))
                {
                    hashMap.put("status", "设计中");
                }
                else if (projectBeanList.get(i).getProjectStatus().equals("did"))
                {
                    hashMap.put("status", "完成");
                }
                else if (projectBeanList.get(i).getProjectStatus().equals("done"))
                {
                    hashMap.put("status", "待审核");
                }
                else if (projectBeanList.get(i).getProjectStatus().equals("checked"))
                {
                    hashMap.put("status", "已审核");
                }
            }
            dataList.add(hashMap);
        }
//        this.runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
                adapter.notifyDataSetChanged();
//            }
//        });
    }
    //方案选择对话框
    private void choiceScheme(int position,ProjectBean projectBean,boolean isChangeScheme)
    {
        List<PointDeviceBean> list = daoSession.getPointDeviceBeanDao().queryBuilder()
                .where(PointDeviceBeanDao.Properties.ProjectId.eq(projectBean.getProjectId()))
                .list();
        List<PolylineDeviceBean> listPolyline = daoSession.getPolylineDeviceBeanDao().queryBuilder()
                .where(PolylineDeviceBeanDao.Properties.ProjectId.eq(projectBean.getProjectId()))
                .list();
        if (list.size() == 0
                || listPolyline.size() == 0 )
        {
            deleteLocalData(projectBean.getProjectId());
            gTaskPresenter.getPoints(projectBean.getProjectId());
            gTaskPresenter.getPolylines(projectBean.getProjectId());
        }
        else  if (UserInfo.getInstance().role.contains("设计"))
        {
            deleteLocalData(projectBean.getProjectId());
            gTaskPresenter.getPoints(projectBean.getProjectId());
            gTaskPresenter.getPolylines(projectBean.getProjectId());
        }
        List<HotLineWorkPlanBean> hotLineWorkPlanBeans = daoSession.getHotLineWorkPlanBeanDao().queryBuilder()
                .where(HotLineWorkPlanBeanDao.Properties.ProjectId.eq(projectBean.getProjectId())).list();
        if (hotLineWorkPlanBeans.size() == 0)
        {
            gProjectPresenter.getHotLineWork(projectBean.getProjectId());
        }
        String schemeName = projectBean.getSchemeName();
        if (UserInfo.getInstance().role.contains("设计"))
        {
//            gTaskPresenter.getPoints(projectBean.getProjectId());
//            gTaskPresenter.getPolylines(projectBean.getProjectId());
            new AlertListDialog.ListBuilder(GTasksActivity.this)
                    .setDividerColorRes(R.color.color_divider)
                    .setDividerHeightRes(R.dimen.dp1)
                    .setTitle("请操作")
                    .setIcon(R.drawable.ic_info)
                    .setItems(new String[]{"成果查看","方案查看", "设计意见"}, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which)
                            {
                                case 0:
                                    //跳转到地图
                                    Intent intent = new Intent(GTasksActivity.this, DesignMapActivity.class);
                                    intent.putExtra("projectId", projectBean.getProjectId());
                                    intent.putExtra("schemeName",schemeName);
                                    startActivity(intent);
                                    break;
                                case 1:
                                    goToScheme(projectBean);
                                    break;
                                case 2:
                                    EditText editText = new EditText(GTasksActivity.this);
                                    editText.setGravity(Gravity.TOP);
                                    editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                                    editText.setMinHeight(40);
                                    editText.setMinLines(10);
                                    editText.setPadding(20,15,20,15);
                                    editText.setFocusable(true);
                                    editText.setFocusableInTouchMode(true);
                                    editText.requestFocus();
                                    GTasksActivity.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                                    new AlertDialog.Builder(GTasksActivity.this)
                                            .setTitle("请输入意见")
                                            .setIcon(R.drawable.ic_info)
                                            .setView(editText)
                                            .setNeutralButton("不通过", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            hideSoftInput(editText);
                                                        }
                                                    });
                                                    String advise = editText.getText().toString();
                                                    if (advise.trim().isEmpty())
                                                    {
                                                        ToastUtils.toast(GTasksActivity.this,"成果提交失败，意见不能为空。。。。");
                                                        return;
                                                    }
                                                    System.out.println(advise);
                                                    projectBean.setRemark(advise);
                                                    projectBean.setProjectStatus("doing");
                                                    updateProjectStatus(position,projectBean,"doing");
                                                }
                                            })
                                            .setPositiveButton("通过", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    String advise = editText.getText().toString();
                                                    System.out.println(advise);
                                                    projectBean.setRemark(advise);
                                                    projectBean.setProjectStatus("checked");
                                                    submitAndUpdateProject(position,projectBean,"checked");
                                                }
                                            })
                                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            hideSoftInput(editText);
                                                        }
                                                    });
                                                    dialog.dismiss();
                                                }
                                            })
                                            .create().show();
                                    break;
                            }
                        }
                    }).setNeutralButton("取消", (dialog, which) -> dialog.dismiss())
                    .create().show();
        }
        else
        {
            if (schemeName == null || schemeName.trim().isEmpty() || isChangeScheme) {
                //显示方案选择
                new AlertListDialog.ListBuilder(GTasksActivity.this)
                        .setDividerColorRes(R.color.color_divider)
                        .setDividerHeightRes(R.dimen.dp1)
                        .setTitle("选择方案")
                        .setIcon(R.drawable.ic_info)
                        .setItems(new String[]{"架空方案", "低压方案"}, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                switch (which) {
                                    case 0:
                                        daoSession.getMyHighVoltageSchemeBeanDao()
                                                .queryBuilder().rx().list()
                                                .observeOn(AndroidSchedulers.mainThread())
                                                .subscribe(new Action1<List<MyHighVoltageSchemeBean>>() {
                                                    @Override
                                                    public void call(List<MyHighVoltageSchemeBean> myHighVoltageSchemeBeans) {
                                                        if (myHighVoltageSchemeBeans.size() == 0)
                                                        {
                                                            Toast.makeText(GTasksActivity.this,"无方案数据，请到方案设置中添加方案",Toast.LENGTH_LONG).show();
                                                            return;
                                                        }
                                                        String[] schemeNames = new String[myHighVoltageSchemeBeans.size()];
                                                        for (int i = 0; i < schemeNames.length; i++) {
                                                            schemeNames[i] = myHighVoltageSchemeBeans.get(i).getSchemeName();
                                                        }
                                                        new AlertListDialog.ListBuilder(GTasksActivity.this)
                                                                .setDividerColorRes(R.color.color_divider)
                                                                .setDividerHeightRes(R.dimen.dp1)
                                                                .setTitle("架空方案")
                                                                .setIcon(R.drawable.ic_info)
                                                                .setItems(schemeNames, new DialogInterface.OnClickListener() {
                                                                    @Override
                                                                    public void onClick(DialogInterface dialog, int which) {
                                                                        dialog.dismiss();
                                                                        projectBean.setSchemeName(myHighVoltageSchemeBeans.get(which).getSchemeName());
                                                                        projectBean.setSchemaType("high");
                                                                        saveScheme(position, projectBean);
                                                                    }
                                                                }).create().show();
                                                    }
                                                });
                                        break;
                                    case 1:
                                        daoSession.getMyLowVoltageSchemeBeanDao()
                                                .queryBuilder().rx().list()
                                                .observeOn(AndroidSchedulers.mainThread())
                                                .subscribe(new Action1<List<MyLowVoltageSchemeBean>>() {
                                                    @Override
                                                    public void call(List<MyLowVoltageSchemeBean> myLowVoltageSchemeBeans) {
                                                        if (myLowVoltageSchemeBeans.size() == 0)
                                                        {
                                                            Toast.makeText(GTasksActivity.this,"无方案数据，请到方案设置中添加方案",Toast.LENGTH_LONG).show();
                                                            return;
                                                        }
                                                        String[] schemeNames = new String[myLowVoltageSchemeBeans.size()];
                                                        for (int i = 0; i < schemeNames.length; i++) {
                                                            schemeNames[i] = myLowVoltageSchemeBeans.get(i).getSchemeName();
                                                        }
                                                        new AlertListDialog.ListBuilder(GTasksActivity.this)
                                                                .setDividerColorRes(R.color.color_divider)
                                                                .setDividerHeightRes(R.dimen.dp1)
                                                                .setTitle("低压方案")
                                                                .setIcon(R.drawable.ic_info)
                                                                .setItems(schemeNames, new DialogInterface.OnClickListener() {
                                                                    @Override
                                                                    public void onClick(DialogInterface dialog, int which) {
                                                                        dialog.dismiss();
                                                                        projectBean.setSchemeName(myLowVoltageSchemeBeans.get(which).getSchemeName());
                                                                        projectBean.setSchemaType("low");
                                                                        saveScheme(position, projectBean);
                                                                    }
                                                                }).create().show();
                                                    }
                                                });
                                        break;
                                }
                            }
                        })
                        .create().show();
            } else {
                new AlertListDialog.ListBuilder(GTasksActivity.this)
                        .setDividerColorRes(R.color.color_divider)
                        .setDividerHeightRes(R.dimen.dp1)
                        .setTitle("请操作")
                        .setIcon(R.drawable.ic_info)
                        .setItems(new String[]{"完成设计", "进行设计", "上传", "修改方案", "清空设计数据","工程信息","设计综述","带电作业方案确认"
                        }, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        Log.e(GTasksActivity.class.getName(), "修改数据状态为完成");
                                        updateProjectStatus(position, projectBean, "did");
                                        break;
                                    case 1:
                                        //跳转到地图
                                        Intent intent = new Intent(GTasksActivity.this, DesignMapActivity.class);
                                        intent.putExtra("projectId", projectBean.getProjectId());
                                        intent.putExtra("schemeName",schemeName);
                                        startActivity(intent);
                                        break;
                                    case 2:
                                        //进行上传;
                                        Log.e(GTasksActivity.class.getName(), "修改数据状态为已经上传");
//                                        projectBean.setUserName(UserInfo.getInstance().userName);
//                                        updateProjectStatus(position, projectBean, "done");
                                        projectBean.setProjectStatus("done");
                                        uploadDeviceData(projectBean,position);
                                        break;
                                    case 3:
                                        //修改方案名称;
                                        choiceScheme(position,projectBean,true);
                                        break;
                                    case 4:
                                        //清空设计数据数据;
                                        gTaskPresenter.deleteDevice(projectBean.getProjectId());
                                        break;
                                    case 5:
                                        //跳转工程总计
                                        Intent intent1 = new Intent(GTasksActivity.this, ProjectInfoActivity.class);
                                        intent1.putExtra("projectId", projectBean.getProjectId());
                                        startActivity(intent1);
                                        break;
                                    case 6:
                                        //跳转到工程总结
                                        Intent intent2 = new Intent(GTasksActivity.this, ProjectTotal.class);
                                        intent2.putExtra("projectId", projectBean.getProjectId());
                                        startActivity(intent2);
                                        break;
                                    case 7:
                                        //带电作业方案确认
                                        Intent intent3 = new Intent(GTasksActivity.this, ProjectHotLineWorkActivity.class);
                                        intent3.putExtra("projectId", projectBean.getProjectId());
                                        startActivity(intent3);
                                        break;
                                }
                            }
                        }).create().show();
            }
        }
    }
    //更新项目中的方案名称
    private void saveScheme(int index,ProjectBean projectBean) {
        projectBean.setUserName(UserInfo.getInstance().userName);
        gTaskPresenter.updateProject(projectBean,2,index);
    }
    // 上传数据
    private void uploadDeviceData(ProjectBean projectBean,int position)
    {
        String projectId = projectBean.getProjectId();
        List<PointDeviceBean> pointDeviceBeanList = daoSession.getPointDeviceBeanDao().queryBuilder()
                .where(PointDeviceBeanDao.Properties.ProjectId.eq(projectId)).list();
        List<PolylineDeviceBean> polylineDeviceBeanList = daoSession.getPolylineDeviceBeanDao().queryBuilder()
                .where(PolylineDeviceBeanDao.Properties.ProjectId.eq(projectId)).list();
//        gTaskPresenter.uploadPoints(pointDeviceBeanList);
//        gTaskPresenter.uploadPolylines(polylineDeviceBeanList);
        gTaskPresenter.uploadDeviceData(4,pointDeviceBeanList,polylineDeviceBeanList,projectBean,position);
    }

    //修改项目状态为完成
    private void updateProjectStatus(int index, ProjectBean projectBean, String status) {
        projectBean.setProjectStatus(status);
        gTaskPresenter.updateProject(projectBean,1,index);
    }

    //进行项目提交到评审平台后再更新项目状态
    private void submitAndUpdateProject(int index, ProjectBean projectBean, String status)
    {
        projectBean.setProjectStatus(status);
        gTaskPresenter.submitToReview(projectBean,1,index);
    }

    private void goToScheme(ProjectBean projectBean)
    {
        if (projectBean == null)
        {
            ToastUtils.toast(GTasksActivity.this,"项目信息为空,无法查看....");
        }
        String schemeName = projectBean.getSchemeName();
        switch (projectBean.getSchemaType())
        {
            case "high":
                MyHighVoltageSchemeBean myHighVoltageSchemeBean = daoSession
                        .getMyHighVoltageSchemeBeanDao()
                        .queryBuilder()
                        .where(MyHighVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                MyHighVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName()))
                        .unique();
                Intent intent = new Intent(GTasksActivity.this, MyHighVoltageSchemeEditActivity.class);
                intent.putExtra("code", "1");
                intent.putExtra("bean", myHighVoltageSchemeBean);
                startActivity(intent);
                break;
            case "low":
                MyLowVoltageSchemeBean myLowVoltageSchemeBean = daoSession.getMyLowVoltageSchemeBeanDao()
                        .queryBuilder()
                        .where(MyLowVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                MyLowVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName()))
                        .unique();
                Intent intent1 = new Intent(GTasksActivity.this, MyLowVoltageSchemeEditActivity.class);
                intent1.putExtra("code", "1");
                intent1.putExtra("bean", myLowVoltageSchemeBean);
                startActivity(intent1);
                break;
        }
    }

    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {

            Window _window = getWindow();
            WindowManager.LayoutParams params = _window.getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
            _window.setAttributes(params);
        }
    }

    private void  hideSoftInput(EditText editText){
        InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(),  InputMethodManager.HIDE_NOT_ALWAYS);
    }

    private void deleteLocalData(String projectId)
    {
        List<PointDeviceBean> list = daoSession.getPointDeviceBeanDao().queryBuilder()
                .where(PointDeviceBeanDao.Properties.ProjectId.eq(projectId))
                .list();
        daoSession.getPointDeviceBeanDao().deleteInTx(list);
        List<PolylineDeviceBean> list1 = daoSession.getPolylineDeviceBeanDao().queryBuilder()
                .where(PolylineDeviceBeanDao.Properties.ProjectId.eq(projectId)).list();
        daoSession.getPolylineDeviceBeanDao().deleteInTx(list1);
    }
}